#!/usr/bin/env python
# vim: set fileencoding=UTF-8

###############################################################################
#
# filename:  utils.py
#
# purpose:   Utilities for XazeInstaller
#
# author(s): Alessandro Molari (mola89.molarulez.com)
#            Luca Molari
#
# license:   This file is licensed under the GPLv2
#            For more informations read:
#            http://www.gnu.org/licenses/gpl-2.0.txt
#
# part of:   This file is part of the XazeInstaller
#
###############################################################################


"""
Utilities for XazeInstaller
"""



import os
import pwd
import grp



class FileInfo:
    """
    Manipulate file informations
    """

    def __init__(self, currentuser):
        self.currentuser = currentuser

    def get_currentuserhome(self):
        if self.currentuser == "root":
            cu_dir  = os.path.abspath("/root")
        else:
            cu_dir = os.path.abspath(os.path.join("/home", self.currentuser))
        return cu_dir

    def setup_permissions(self, perms_space, \
                          filepath, get_permissions, \
                          exc_tuple = (), print_on_permsnotfound = False, \
                          get_defaultpermissions = None):
        """
        Execute the 'get_permissions' method to get int (base 8) permissions.
        If an exception that it is in 'exc_tuple' is raised:
            1- if 'print_on_permsnotfound' is True, it prints that it uses the
               default values, then if 'get_defaultpermissions' is True it
               calls it
            2- overwise it doesn't do anything
        If it doesn't raise an exception, it sets permissions on 'filepath' to
            the return result of 'get_permissions()'
        """

        try:
            perms = get_permissions()
        except exc_tuple:
            if print_on_permsnotfound:
                print "%s>>> Used default permissions for %s" % (perms_space, filepath)
                if not get_defaultpermissions is None:
                    get_defaultpermissions()
        else:
            os.chmod(filepath, perms)
            print "%s>>> Changed mode of %s to %s" % (perms_space, filepath, oct(perms))


    def setup_owner(self, owner_space, \
                    filepath, get_ownername, \
                    exc_tuple = (), print_on_ownernotfound = False, \
                    get_defaultowner = None):
        """
        Execute the 'get_ownername' method to get the owner.
        If an exception that it is in the 'exc_tuple' is raised:
            1- if 'print_on_ownernotfound' is True, it prints that it uses the
               default values, then if 'get_defaultowner' is True it
               calls it
            2- otherwise it doesn't do anything
        If it doesn't raise an exception, it sets permissions on 'filepath' to
            the return result of 'get_owner()'
        """

        try:
            uname = get_ownername()
            if uname == "#USER#":
                uname = self.currentuser
        except exc_tuple:
            if print_on_ownernotfound:
                print "%s>>> Used default owner for %s" % (owner_space, filepath)
                if not get_defaultowner is None:
                    get_defaultowner()
        else:
            uid = pwd.getpwnam(uname).pw_uid
            os.chown(filepath, uid, -1)
            print "%s>>> Changed owner of %s to %s (uid = %s)" % \
                   (owner_space, filepath, uname, uid)


    def setup_group(self, group_space, \
                    filepath, get_groupname, \
                    exc_tuple = (), print_on_groupnotfound = False, \
                    get_defaultgroup = None):
        """
        Execute the 'get_groupname' method to get the owner.
        If an exception that it is in the 'exc_tuple' is raised:
            1- if 'print_on_ownernotfound' is True, it prints that it uses the
               default values, then if 'get_defaultgroup' is True it
               calls it
            2- otherwise it doesn't do anything
        If it doesn't raise an exception, it sets permissions on 'filepath' to
            the return result of 'get_owner()'
        """

        try:
            gname = get_groupname()
            if gname == "#USERS#":
                if self.currentuser == "root":
                    gname = "root"
                else:
                    gname = "users"
        except exc_tuple:
            if print_on_groupnotfound:
                print "%s>>> Used default group for %s" % (group_space, filepath)
                if not get_defaultgroup is None:
                    get_defaultgroup()
        else:
            gid = grp.getgrnam(gname).gr_gid
            os.chown(filepath, -1, gid)
            print "%s>>> Changed group of %s to %s (gid = %s)" % \
                (group_space, filepath, gname, gid)


